import { useState, useEffect, useRef, RefObject, useCallback } from 'react';
import { VideoCourtSchema } from '@src/components/schema/videoCourt'
import OperateModal from './components/operateModal'
import style from './index.module.less'
import { Form, Row, Col, Input, Button, Table, message, Radio, DatePicker, FormInstance, TablePaginationConfig, Select } from 'antd';
import moment from 'moment'
import { addWindow } from '@redux/actions/tab'
import { getListRequest, delRequest, updateRequest, addRequest } from './ajax'
import { awaitWrap, confirmAction } from '@src/assets/js/tool'
import { CaseSchema } from '@src/components/schema/caseSchema'
import CaseNoRender from '@src/components/caseNoRender'
import { Dispatch } from 'redux'
import { useDispatch, useSelector } from 'react-redux';
import { ColumnType } from 'antd/lib/table';
import { INIT_BASIC_STATE } from '../../../../../redux/reducers/basic';

const { Item } = Form
const { Option } = Select
const layout = {
  labelCol: { flex: '72px' }
}

// 获取表格字段配置
function getColumns (dispatch: Dispatch, setModfiyData: (v: VideoCourtSchema) => void, setVisible: (v: boolean) => void, refreshFn: () => void): Array<ColumnType<VideoCourtSchema>> {
  const list: Array<ColumnType<VideoCourtSchema>> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 130,
      render: (v: string, l: VideoCourtSchema) => {
        return <CaseNoRender data={l as unknown as CaseSchema} />
      }
    },
    {
      title: '申请人',
      dataIndex: 'applicant_name',
      key: 'applicant_name',
      width: 150
    },
    {
      title: '被申请人',
      dataIndex: 'respondent_name',
      key: 'respondent_name',
      width: 150
    },
    {
      title: '开始时间',
      dataIndex: 'begin_datetime',
      key: 'begin_datetime',
      width: 150,
      render: (v: number) => {
        return v ? moment(v * 1000).format('YYYY-MM-DD HH:mm') : ''
      }
    },
    {
      title: '结束时间',
      dataIndex: 'end_datetime',
      key: 'end_datetime',
      width: 150,
      render: (v: number) => {
        return v ? moment(v * 1000).format('YYYY-MM-DD HH:mm') : ''
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120
    },
    {
      title: '经办人',
      dataIndex: 'processer',
      key: 'processer',
      width: 120
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 100,
      render: (value: string, line: VideoCourtSchema) => {
        const modiable = ['完成', '取消'].indexOf(line.status) === -1
        const cancelable = line.status === '预约'
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => openDetail(line, dispatch)}>详情</span>
          </span>
        )
      }
    }
  ]
  return list
}

// 查看详情
function openDetail (data: VideoCourtSchema, dispatch: Dispatch) {
  dispatch(addWindow({ id: `caseMeeting-${data.id}`, title: `视频庭审-${data.caseno_desc}`, componentName: 'VideoMeetingDetail', forceRefresh: true, meta: { id: data.id, caseid: data.caseid } }))
}

async function delHandle (line: VideoCourtSchema, refreshFn: () => void) {
  const hide = message.loading('取消中')
  const [e] = await awaitWrap(delRequest(line.id))
  hide()
  if (e === null) {
    message.success('取消成功')
    refreshFn()
  }
}

function changeMeeting (o: { [k: string]: any }, afterUpdate: () => void, afterAdd: (t: string) => void, hide: () => void) {
  const { id } = o
  o.begin_datetime = Math.floor(o.begin_datetime.valueOf() / 1000)
  o.end_datetime = Math.floor(o.end_datetime.valueOf() / 1000)
  delete o.caseno_desc
  if (id) {
    modifyMeetingRequest(o, afterUpdate, hide)
  } else {
    addMeetingRequest(o, () => afterAdd(o.type), hide)
  }
}

async function modifyMeetingRequest (o: { [k: string]: any }, refreshFn: () => void, hide: () => void) {
  const h = message.loading('提交中')
  const [e] = await awaitWrap(updateRequest(o))
  h()
  if (e === null) {
    message.success('修改成功')
    refreshFn()
    hide()
  }
}

async function addMeetingRequest (o: { [k: string]: any }, refreshFn: () => void, hide: () => void) {
  const h = message.loading('提交中')
  const [e] = await awaitWrap(addRequest(o))
  h()
  if (e === null) {
    message.success('新增成功')
    setTimeout(() => refreshFn(), 100)
    hide()
  }
}

// 获取condition
function getCondition (form: { [k: string]: any }, status: string) {
  const condition = []
  if (status === '进行中') {
    condition.push({ k: 'm.status', o: 'in', v: '预约,会议开始,会议结束' })
  } else if (status === '作废') {
    condition.push({ k: 'm.status', o: 'in', v: '取消,作废' })
  } else {
    condition.push({ k: 'm.status', o: '=', v: '完成' })
  }
  if (form.type !== '全部') {
    condition.push({ k: 'm.type', o: '=', v: form.type })
  }
  if (form.use) {
    condition.push({ k: 'm.use', o: 'in', v: form.use })
  }
  if (form.caseno_desc) {
    condition.push({ k: 'c.caseno_desc', o: 'like', v: `%${form.caseno_desc}%` })
  }
  if (form.applicant_name) {
    condition.push({ K: 'c.applicant_name', o: 'like', v: `%${form.applicant_name}%` })
  }
  if (form.respondent_name) {
    condition.push({ K: 'c.respondent_name', o: 'like', v: `%${form.respondent_name}%` })
  }
  if (form.beginTime) {
    condition.push({ k: 'm.begin_datetime', o: '>=', v: Math.floor(moment(form.beginTime.format('YYYY-MM-DD')).valueOf() / 1000) })
  }
  if (form.endTime) {
    condition.push({ k: 'm.end_datetime', o: '<=', v: Math.floor(moment(form.endTime.format('YYYY-MM-DD') + ' 23:59:59').valueOf() / 1000) })
  }
  return condition
}

async function getTableData (
  o: { [k: string]: any } | null,
  id: string,
  formRef: RefObject<FormInstance>,
  current: number,
  pageSize: number,
  status: string,
  setLoading: (v: boolean) => void,
  setList: (v: VideoCourtSchema[]) => void,
  setTotal: (v: number) => void
) {
  const form = o || formRef.current?.getFieldsValue()
  const condition = getCondition(form, status)
  const data = {
    page: current,
    limit: pageSize,
    condition: JSON.stringify(condition)
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(data))
  setLoading(false)
  if (e === null && d !== null) {
    d.list.forEach((li, i) => {
      li.index = ((current as number) - 1) * (pageSize as number) + i + 1
    })
    setList(d.list)
    setTotal(d.total)
  }
}

// 重置表格
function resetHandle (
  formRef: RefObject<FormInstance>,
  setCurrent: (v: number) => void,
  setFormData: (v: any) => void
) {
  formRef.current?.resetFields()
  setCurrent(1)
  setFormData({ type: '正式' })
}

function tableChange (v: TablePaginationConfig, setCurrent: (v: number) => void, setPageSize: (v: number) => void) {
  const { current, pageSize } = v
  setCurrent(current || 1)
  setPageSize(pageSize || 10)
}

interface Props {
  title: string
}

function Main ({ title }: Props) {
  const formRef = useRef<FormInstance>(null)
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<VideoCourtSchema | null>(null)
  const [status, setStatus] = useState('进行中')
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<VideoCourtSchema[]>([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [pagination, setPagination] = useState<TablePaginationConfig>()
  const [formData, setFormData] = useState({ type: '全部' })
  const { id } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
    return {
      id: state.basic.userInfo.id
    }
  })
  const refreshFn = useCallback(() => { getTableData(formData, id, formRef, current, pageSize, status, setLoading, setList, setTotal) }, [formData, id, formRef, current, pageSize, status])
  const dispatch = useDispatch()
  useEffect(() => {
    setPagination({
      current,
      pageSize,
      total,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    })
  }, [current, pageSize, total])
  useEffect(() => {
    refreshFn()
  }, [status, formData, pageSize, current])
  return (
    <div className={style.container}>
      <OperateModal visible={visible} data={modifyData} hide={() => { setVisible(false); setModifyData(null) }} onChange={d => changeMeeting(d, refreshFn, (t: string) => { setCurrent(1); setStatus('进行中'); setFormData({...formData, type: t}); formRef.current?.setFieldsValue({ type: t }) }, () => { setVisible(false); setModifyData(null); })} />
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <div className={style['search-container']}>
        <div className={style['search-form']}>
          <Form name='my_case_manage' {...layout} initialValues={{ type: '全部' }} ref={formRef} onFinish={v => { setCurrent(1); setFormData(v) }}>
            <Row gutter={24}>
              <Col span={8}>
                <Item label='案号' name='caseno_desc'>
                  <Input placeholder='请输入案号' />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='申请人' name='applicant_name'>
                  <Input placeholder='请输入申请人' />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='被申请人' name='respondent_name'>
                  <Input placeholder='请输入被申请人' />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='开始日期' name='beginTime'>
                  <DatePicker className={style.full} placeholder='请选择日期' />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='结束日期' name='endTime'>
                  <DatePicker className={style.full} placeholder='请选择日期' />
                </Item>
              </Col>
              <Col span={8}>
                <Item label='用途' name='use'>
                  <Select placeholder='请选择用途'>
                    <Option value='开庭'>开庭</Option>
                    <Option value='合议'>合议</Option>
                    <Option value='调解'>调解</Option>
                  </Select>
                </Item>
              </Col>
              <Col span={8}>
                <Item label='庭审类型' name='type'>
                  <Select placeholder='请选择用途'>
                    <Option value='全部'>全部</Option>
                    <Option value='测试'>测试</Option>
                    <Option value='正式'>正式</Option>
                  </Select>
                </Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={16} />
              <Col span={8}>
                <Item>
                  <div className={style['search-btns']}>
                    <Button type='primary' ghost htmlType='submit'>搜索</Button>
                    <Button htmlType='reset' onClick={() => resetHandle(formRef, setCurrent, setFormData)}>重置
                    </Button>
                    {/* {this.renderToggleBtns()} */}
                  </div>
                </Item>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className={style['table-btns-line']}>
        <span />
        <div className={style['table-tabs-container']}>
          <Radio.Group value={status} onChange={v => {
            setCurrent(1)
            setStatus(v.target.value)
          }}>
            <Radio.Button value='进行中'>进行中</Radio.Button>
            <Radio.Button value='完成'>完成</Radio.Button>
            <Radio.Button value='作废'>取消/作废</Radio.Button>
          </Radio.Group>
        </div>
      </div>
      <div className={style['table-container']}>
        <Table rowKey='id' loading={loading} columns={getColumns(dispatch, setModifyData, setVisible, refreshFn)} dataSource={list} pagination={pagination} onChange={(v) => tableChange(v, setCurrent, setPageSize)} />
      </div>
    </div>
  )
}

export default Main
